/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.vng.zing.zprofilefrontend.model;

import com.vng.zing.zprofilefrontend.common.Util;
import com.vng.zing.calc.thrift.Profile;
import com.vng.zing.calc.thrift.ProfileSession;
import com.vng.zing.calc.thrift.ROLE;
import com.vng.zing.logger.ZLogger;
import com.vng.zing.stats.Profiler;
import com.vng.zing.stats.ThreadProfiler;
import com.vng.zing.stats.monitor.common.TemplateManager;
import static com.vng.zing.zprofilefrontend.model.BaseModel.checkLogIn;
import hapax.Template;
import hapax.TemplateDataDictionary;
import hapax.TemplateDictionary;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;

/**
 *
 * @author namhh
 */
public class InfoModel extends BaseModel {

    private static final Logger _Logger = ZLogger.getLogger(LogInModel.class);
    public static final InfoModel Instance = new InfoModel();

    private InfoModel() {
    }

    @Override
    public void process(HttpServletRequest req, HttpServletResponse resp) {
        ThreadProfiler profiler = Profiler.getThreadProfiler();

        resp.setContentType("text/html; charset=UTF-8");
        PrintWriter out = null;
        try {
            out = resp.getWriter();
            profiler.push(this.getClass(), "output");
            if (null != req.getParameter("id")) {
                String str_Id = req.getParameter("id");
                if (null == str_Id || !Util.isInteger(str_Id)) {
                    showError(out, getProperties().get("en.invalidParams"));
                } else {
                    int profileInfoId = Integer.parseInt(str_Id);
                    ProfileSession profileSession = checkLogIn(req);
                    if (null != profileSession) {
                        Profile loggedInprofile = getClientWithCache().getaLoad(profileSession.getId());
                        if (profileInfoId == profileSession.getId() || loggedInprofile.getRole().equals(ROLE.ADMIN)) {
                            /////////////
                            Profile profileInfo = getClientWithCache().getaLoad(profileInfoId);
                            TemplateDataDictionary dic = TemplateDictionary.create();
                            setHeaderFooter("ZProfile - Profile Info", dic, loggedInprofile);
                            dic.setVariable("PROFILE_ID", String.format("%s", profileInfo.getId()));
                            dic.setVariable("USERNAME", profileInfo.getUsername());
                            dic.setVariable("GENDER", profileInfo.getGender().name());
                            dic.setVariable("DISPLAY_NAME", profileInfo.getDisplayName());
                            dic.setVariable("EMAIL", profileInfo.getEmail());
                            dic.setVariable("MOBILE", profileInfo.getMobileNumber());
                            dic.setVariable("DATE_OF_BIRTH", Util.toDate(profileInfo.getDateOfBirth()));
                            Map<Short, String> cities = CityModel.getInstance().getAllCities();
                            dic.setVariable("CITY", cities.get(profileInfo.getCityId()));
                            dic.setVariable("CREATED_DATE", Util.toDate(profileInfo.getCreatedDate()));
                            dic.setVariable("MODIFIED_DATE", Util.toDate(profileInfo.getModifiedDate()));
                            dic.setVariable("MODIFIED_BY", profileInfo.getModifiedBy());
                            dic.setVariable("STATUS", profileInfo.getStatus().name());
                            dic.setVariable("ROLE", profileInfo.getRole().name());
                            for (Map.Entry< Short, String> entry : CityModel.getInstance().getAllCities().entrySet()) {
                                TemplateDataDictionary sliceCities = dic.addSection("SLICE_CITY");
                                sliceCities.setVariable("CITY_ID", String.format("%s", entry.getKey()));
                                sliceCities.setVariable("CITY", entry.getValue());
                                if (entry.getKey().equals(profileInfo.getCityId())) {
                                    sliceCities.setVariable("SELECTED", "selected");
                                }
                            }
                            Long now = new Date().getTime() / 1000;
                            long age = (now.intValue() - profileInfo.getDateOfBirth()) / (3600 * 24 * 365);
                            dic.setVariable("AGE", String.format("%s", age));
                            dic.setVariable("NAME", (null != profileInfo.getDisplayName() && !"".equals(profileInfo.getDisplayName()) ? profileInfo.getDisplayName() : profileInfo.getUsername()));
                            Template info;
                            if (profileSession.getId() == profileInfoId) {
                                if (profileInfo.getRole().equals(ROLE.ADMIN)) {
                                    info = TemplateManager.getTemplate("admin-info");
                                } else {
                                    info = TemplateManager.getTemplate("info");
                                }
                            } else {
                                info = TemplateManager.getTemplate("admin-view-info");
                            }
                            out.println(info.renderToString(dic));
                            ////////////
                        } else {
                            showError(out, getProperties().get("en.persissionDenied"));
                        }

                    } else {
                        resp.sendRedirect("/login");
                    }
                }

            } else {
                showError(out, "Invalid parameter.");
            }

            profiler.pop(this.getClass(), "output");
        } catch (Exception ex) {
            _Logger.error(null, ex);
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

}
